package com.qimu.saiyou.controller;

import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.qimu.saiyou.annotation.AuthCheck;
import com.qimu.saiyou.common.BaseResponse;
import com.qimu.saiyou.common.DeleteRequest;
import com.qimu.saiyou.common.ErrorCode;
import com.qimu.saiyou.common.ResultUtils;
import com.qimu.saiyou.constant.UserConstant;
import com.qimu.saiyou.exception.BusinessException;
import com.qimu.saiyou.exception.ThrowUtils;
import com.qimu.saiyou.model.dto.competition.CompetitionAddRequest;
import com.qimu.saiyou.model.dto.competition.CompetitionEditRequest;
import com.qimu.saiyou.model.dto.competition.CompetitionQueryRequest;
import com.qimu.saiyou.model.dto.competition.CompetitionUpdateRequest;
import com.qimu.saiyou.model.entity.Competition;
import com.qimu.saiyou.model.entity.Team;
import com.qimu.saiyou.model.entity.User;
import com.qimu.saiyou.model.vo.CompetitionVO;
import com.qimu.saiyou.mq.DeadlineMessageProducer;
import com.qimu.saiyou.mq.EndMessageProducer;
import com.qimu.saiyou.service.CompetitionService;
import com.qimu.saiyou.service.TeamService;
import com.qimu.saiyou.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.time.Duration;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 赛事
 *
 *@author: FeiXiang
 * 
 */
@RestController
@RequestMapping("/competition")
@Slf4j
public class CompetitionController {

    @Resource
    private CompetitionService competitionService;

    @Resource
    private UserService userService;

    @Resource
    private TeamService teamService;

    @Resource
    private DeadlineMessageProducer deadlineMessageProducer;

    @Resource
    private EndMessageProducer endMessageProducer;

    // region 增删改查

    /**
     * 创建
     *
     * @param competitionAddRequest
     * @param request
     * @return
     */
    @PostMapping("/add")
    @Transactional(rollbackFor = Exception.class)
    public BaseResponse<Long> addCompetition(@RequestBody CompetitionAddRequest competitionAddRequest, HttpServletRequest request) {
        if (competitionAddRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Competition competition = new Competition();
        BeanUtils.copyProperties(competitionAddRequest, competition);
        List<String> tags = competitionAddRequest.getTags();
        if (tags != null) {
            competition.setTags(JSONUtil.toJsonStr(tags));
        }
        competitionService.validCompetition(competition, true);
        User loginUser = userService.getLoginUser(request);
        competition.setUserId(loginUser.getId());
        String signUpDeadline = competition.getSignUpDeadline();
        String endTime = competition.getEndTime();
        LocalDateTime now = LocalDateTime.now();
        LocalDateTime deadline = LocalDateTime.parse(signUpDeadline, DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
        Duration duration = Duration.between(now, deadline);
        long millis = duration.toMillis();
        if (!deadline.isAfter(now)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "报名截止时间不能在当前时间之前");
        }
        LocalDateTime endTimeData = LocalDateTime.parse(endTime, DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
        Duration end = Duration.between(now, endTimeData);
        if (endTimeData.isBefore(deadline)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "结束时间不能在报名截止时间之前");
        }
        boolean result = competitionService.save(competition);
        String jsonStr = JSONUtil.toJsonStr(competition);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        deadlineMessageProducer.sendMessage(jsonStr, (int) millis);
        log.info("【添加报名截止消息成功】" + jsonStr);

        long toMillis = end.toMillis();
        endMessageProducer.sendMessage(jsonStr, (int) toMillis);
        log.info("【添加结束消息成功】" + jsonStr);

        long newCompetitionId = competition.getId();
        return ResultUtils.success(newCompetitionId);
    }

    @GetMapping("/message")
    public BaseResponse<String> message() {
        deadlineMessageProducer.sendMessage("{\"competitionName\":\"赛事测试\",\"examId\":1765610802277916674,\"tags\":\"[\\\"JAVA\\\"]\",\"competitionAvatarUrl\":\"\",\"maxNum\":2,\"userId\":1758381296421081090,\"competitionType\":0,\"competitiveMode\":0,\"teamMaxNum\":5,\"announce\":\"\",\"reward\":\"1\",\"signUpDeadline\":\"2024-04-12 18:48:46\",\"endTime\":\"2024-04-12 18:52:57\"}",20000);

        return ResultUtils.success("success");
    }
    /**
     * 删除
     *
     * @param deleteRequest
     * @param request
     * @return
     */
    @PostMapping("/delete")
    public BaseResponse<Boolean> deleteCompetition(@RequestBody DeleteRequest deleteRequest, HttpServletRequest request) {
        if (deleteRequest == null || deleteRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User user = userService.getLoginUser(request);
        long id = deleteRequest.getId();
        // 判断是否存在
        Competition oldCompetition = competitionService.getById(id);
        ThrowUtils.throwIf(oldCompetition == null, ErrorCode.NOT_FOUND_ERROR);
        // 仅创建人或管理员可删除
        if (!oldCompetition.getUserId().equals(user.getId()) && !userService.isAdmin(request)) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }
        List<Team> teamList = teamService.lambdaQuery()
                .eq(Team::getCurrentCompetitionId, id)
                .list()
                .stream()
                .peek(team -> team.setCurrentCompetitionId(0L)).collect(Collectors.toList());
        teamService.updateBatchById(teamList);
        boolean b = competitionService.removeById(id);
        return ResultUtils.success(b);
    }

    /**
     * 更新（仅管理员）
     *
     * @param competitionUpdateRequest
     * @return
     */
    @PostMapping("/update")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Boolean> updateCompetition(@RequestBody CompetitionUpdateRequest competitionUpdateRequest) {
        if (competitionUpdateRequest == null || competitionUpdateRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Competition competition = new Competition();
        BeanUtils.copyProperties(competitionUpdateRequest, competition);
        List<String> tags = competitionUpdateRequest.getTags();
        if (tags != null) {
            competition.setTags(JSONUtil.toJsonStr(tags));
        }
        // 参数校验
        competitionService.validCompetition(competition, false);
        long id = competitionUpdateRequest.getId();
        // 判断是否存在
        Competition oldCompetition = competitionService.getById(id);
        ThrowUtils.throwIf(oldCompetition == null, ErrorCode.NOT_FOUND_ERROR);
        boolean result = competitionService.updateById(competition);
        return ResultUtils.success(result);
    }

    @PostMapping("/edit")
    public BaseResponse<Boolean> editCompetition(@RequestBody CompetitionEditRequest competitionEditRequest, HttpServletRequest request) {
        if (competitionEditRequest == null || competitionEditRequest.getId() == null || competitionEditRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Competition competition = new Competition();
        BeanUtils.copyProperties(competitionEditRequest, competition);
        List<String> tags = competitionEditRequest.getTags();
        if (tags != null) {
            competition.setTags(JSONUtil.toJsonStr(tags));
        }
        // 参数校验
        competitionService.validCompetition(competition, false);
        User loginUser = userService.getLoginUser(request);
        long id = competitionEditRequest.getId();
        // 判断是否存在
        Competition oldCompetition = competitionService.getById(id);
        ThrowUtils.throwIf(oldCompetition == null, ErrorCode.NOT_FOUND_ERROR);
        // 仅本人或管理员可编辑
        if (!oldCompetition.getUserId().equals(loginUser.getId()) && !userService.isAdmin(loginUser)) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }
        boolean result = competitionService.updateById(competition);
        return ResultUtils.success(result);
    }

    /**
     * 根据 id 获取
     *
     * @param id
     * @return
     */
    @GetMapping("/get/vo")
    public BaseResponse<CompetitionVO> getCompetitionVOById(long id, HttpServletRequest request) {
        if (id <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Competition competition = competitionService.getById(id);
        if (competition == null) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR);
        }
        return ResultUtils.success(competitionService.getCompetitionVO(competition, request));
    }

    /**
     * 分页获取列表（仅管理员）
     *
     * @param competitionQueryRequest
     * @return
     */
    @PostMapping("/list/page")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Page<Competition>> listCompetitionByPage(@RequestBody CompetitionQueryRequest competitionQueryRequest) {
        long current = competitionQueryRequest.getCurrent();
        long size = competitionQueryRequest.getPageSize();
        Page<Competition> competitionPage = competitionService.page(new Page<>(current, size),
                competitionService.getQueryWrapper(competitionQueryRequest));
        return ResultUtils.success(competitionPage);
    }

    /**
     * 分页获取列表（封装类）
     *
     * @param competitionQueryRequest
     * @param request
     * @return
     */
    @PostMapping("/list/page/vo")
    public BaseResponse<Page<CompetitionVO>> listCompetitionVOByPage(@RequestBody CompetitionQueryRequest competitionQueryRequest,
                                                                     HttpServletRequest request) {
        long current = competitionQueryRequest.getCurrent();
        long size = competitionQueryRequest.getPageSize();
        // 限制爬虫
        ThrowUtils.throwIf(size > 20, ErrorCode.PARAMS_ERROR);
        Page<Competition> competitionPage = competitionService.page(new Page<>(current, size),
                competitionService.getQueryWrapper(competitionQueryRequest));
        return ResultUtils.success(competitionService.getCompetitionVOPage(competitionPage, request));
    }

    /**
     * 分页获取当前用户创建的资源列表
     *
     * @param competitionQueryRequest
     * @param request
     * @return
     */
    @PostMapping("/my/list/page/vo")
    public BaseResponse<Page<CompetitionVO>> listMyCompetitionVOByPage(@RequestBody CompetitionQueryRequest competitionQueryRequest,
                                                                       HttpServletRequest request) {
        if (competitionQueryRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User loginUser = userService.getLoginUser(request);
        competitionQueryRequest.setUserId(loginUser.getId());
        long current = competitionQueryRequest.getCurrent();
        long size = competitionQueryRequest.getPageSize();
        // 限制爬虫
        ThrowUtils.throwIf(size > 20, ErrorCode.PARAMS_ERROR);
        Page<Competition> competitionPage = competitionService.page(new Page<>(current, size),
                competitionService.getQueryWrapper(competitionQueryRequest));
        return ResultUtils.success(competitionService.getCompetitionVOPage(competitionPage, request));
    }


    /**
     * 跑步比赛
     *
     * @param id 身份证件
     * @return {@link BaseResponse}<{@link Boolean}>
     */
    @PostMapping("/running")
    @AuthCheck(anyRole = {"admin", "teacher"})
    public BaseResponse<Boolean> runningCompetition(long id) {
        if (ObjectUtils.isEmpty(id) || id <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Competition competition = competitionService.getById(id);
        ThrowUtils.throwIf(competition == null, ErrorCode.NOT_FOUND_ERROR);
        competition.setCompetitionStatus("running");
        return ResultUtils.success(competitionService.updateById(competition));
    }

    /**
     * 取消比赛
     *
     * @param id 身份证件
     * @return {@link BaseResponse}<{@link Boolean}>
     */
    @PostMapping("/cancel")
    @AuthCheck(anyRole = {"admin", "teacher"})
    public BaseResponse<Boolean> cancelCompetition(long id) {
        if (ObjectUtils.isEmpty(id) || id <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Competition competition = competitionService.getById(id);
        ThrowUtils.throwIf(competition == null, ErrorCode.NOT_FOUND_ERROR);
        competition.setCompetitionStatus("cancel");
        return ResultUtils.success(competitionService.updateById(competition));
    }

    /**
     * 终止
     *
     * @param id 身份证件
     * @return {@link BaseResponse}<{@link Boolean}>
     */
    @PostMapping("/end")
    @AuthCheck(anyRole = {"admin", "teacher"})
    public BaseResponse<Boolean> finishCompetition(long id) {
        if (ObjectUtils.isEmpty(id) || id <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Competition competition = competitionService.getById(id);
        ThrowUtils.throwIf(competition == null, ErrorCode.NOT_FOUND_ERROR);
        competition.setCompetitionStatus("end");
        return ResultUtils.success(competitionService.updateById(competition));
    }

    // endregion

}
